package com.mugui.spring.net.sys;

import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.stereotype.Component;

import com.mugui.spring.base.Manager;

import cn.hutool.core.util.StrUtil;

@Component
public class SysLogManager extends Manager<String, SysLogApi> {

	public static final String FORWARD_LOG = "forward_log";
	public static final String DEFAULT_LOG = "default_log";
	public static final String CACHE_LOG = "cache_log";
	public static final String NETBAG_LOG = "netbag_log";
	public static final String FILTER_LOG = "filter_log";
	public static final String LISTENER_LOG = "listener_log";
	public static final String TASK_LOG = "task_log";
	public static final String[] logs = { TASK_LOG, FORWARD_LOG, DEFAULT_LOG, FORWARD_LOG, CACHE_LOG, NETBAG_LOG,
			LISTENER_LOG, FILTER_LOG };

	public SysLogApi getSysLog(String syslogname) {
		try {
			for (String id : logs) {
				if (id.equals(syslogname)) {
					return (SysLogApi) invokeFunction(toLogName(id));
				}
			}
			SysLogApi object = (SysLogApi) get(syslogname);
			if (object != null) {
				return object;
			}
			return initSysLog(syslogname);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public SysLogApi initSysLog(String syslogname) {
		SysLogApi b = (SysLogApi) get(syslogname);
		if (b == null) {
			synchronized (getClass()) {
				if (b == null) {
					ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
					reference.setInterface(SysLogApi.class);
					reference.setVersion("");
					reference.setGeneric(true);
					reference.setGroup(syslogname);
					GenericService genericService = reference.get();
					add(syslogname, b = new SysLogImpl(genericService));
				}
			}
		}
		return b;
	}

	private String toLogName(String id) {
		String[] split = id.split("_");
		String name = "";
		for (String strs : split) {
			name += StrUtil.upperFirst(strs);
		}
		return name;
	}

	public SysLogApi ForwardLog() {
		return initSysLog(FORWARD_LOG);
	}

	public SysLogApi DefaultLog() {
		return initSysLog(DEFAULT_LOG);
	}

	public SysLogApi CacheLog() {
		return initSysLog(CACHE_LOG);
	}

	public SysLogApi NetbagLog() {
		return initSysLog(NETBAG_LOG);
	}

	public SysLogApi ListenerLog() {
		return initSysLog(LISTENER_LOG);
	}

	public SysLogApi FilterLog() {
		return initSysLog(FILTER_LOG);
	}
	public SysLogApi TaskLog() {
		return initSysLog(TASK_LOG);
	}
}
